package com.example.cdctestsystem.managecontroller;

import com.example.cdctestsystem.pojo.Admin;
import com.example.cdctestsystem.service.AdminService;
import com.example.cdctestsystem.util.MailUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/manage/login")
public class AdminController {
    @Resource
    private AdminService adminService;

    @RequestMapping("login")
    public void login() {
    }


    @RequestMapping("index")
    public String adminLogin(Admin admin, HttpServletRequest request) {
        Admin admin1 = adminService.adminLogin(admin);

        if (admin1 != null) {
            request.getSession().setAttribute("loginAdmin", admin1);
            return "/manage/index";
        } else {
            return "/manage/login/login";
        }
    }

    @RequestMapping("yanzheng")
    @ResponseBody
    public String yanzheng(HttpServletRequest request, HttpServletResponse response) {
        String code = MailUtil.getMailUtil().createFoursRandom();
        HttpSession session = request.getSession();
        session.setAttribute("code", code);
        return code;
    }

    @RequestMapping("panduan")
    @ResponseBody
    public void panduan(String code, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        String sessioncode = (String) session.getAttribute("code");
        boolean flag = sessioncode.equals(code);
//        System.out.println("code:"+code);
//        System.out.println("sessioncode:"+sessioncode);
//        System.out.println(flag);
        session.setAttribute("flag", flag);//把判断结果保存到session中
        try {
            response.getWriter().print(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("denglu")
    @ResponseBody
    public boolean denglu(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        if (session.getAttribute("flag") == null) {//session中没有东西，还没验证
            return false;
        }
//        System.out.println(session.getAttribute("flag"));
        return (boolean) session.getAttribute("flag");
    }


    //退出
    @RequestMapping("exit")
    public void exit(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        String path = request.getContextPath();
        response.sendRedirect("/manage/login/login");
    }


}
